<template>
    <div class="login">
        <van-nav-bar :title="isLogin ? '登录' : '注册'" left-text="返回" left-arrow @click-left="onClickLeft" />
        <van-form @submit="onSubmit">
            <van-cell-group inset>
                <van-field v-model.trim="userData.username" name="用户名" label="用户名" placeholder="用户名"
                    :rules="[{ required: true, message: '请填写用户名' }]" />
                <van-field v-model.trim="userData.password" type="password" name="密码" label="密码" placeholder="密码"
                    :rules="[{ required: true, message: '请填写密码' }]" />
                <van-field v-if="!isLogin" v-model.trim="userData.rePassword" type="password" name="确认密码" label="确认密码"
                    placeholder="确认密码" :rules="[
                        { required: true, message: '请填写确认密码' },
                        { validator: validateConfirmPassword },
                    ]" />
            </van-cell-group>
            <van-cell-group inset>
                <span @click="changeLoginType">{{
                    isLogin ? "还没有账号？" : "已有账号？"
                }}</span>
            </van-cell-group>
            <div style="margin: 16px">
                <van-button round block type="primary" native-type="submit">
                    {{ isLogin ? "登录" : "注册" }}
                </van-button>
            </div>
        </van-form>
    </div>
</template>

<script setup>
import { ref } from "vue";
import { loginService, registerService } from "@/apis/user";
import { useTokenStore } from "@/stores/token";
import { useRouter } from "vue-router";
const isLogin = ref(true);
const tokenStore = useTokenStore();
const router = useRouter();
const userData = ref({
    username: "",
    password: "",
    rePassword: "",
});
const onSubmit = async () => {
    let res = await (isLogin.value ? loginService : registerService)(userData.value);
    // 登录成功，保存token
    tokenStore.setToken(res.data.token);
    // 跳转页面
    router.push({ name: "my" });
};
const onClickLeft = () => {
    history.back();
};
const changeLoginType = () => {
    // 清空表单
    userData.value = {
        username: "",
        password: "",
        rePassword: "",
    };
    // 切换登录注册状态
    isLogin.value = !isLogin.value;
};
const validateConfirmPassword = (val) => {
    if (val !== userData.value.password) {
        return "两次密码输入不一致";
    }
    return true;
};
</script>
<style scoped>
.van-form {
    padding: 20px;
}
</style>
